﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using QuotationSoftware.DialogForm;
using Business;
using Common;

namespace QuotationSoftware
{
    public partial class mForm : Form
    {
        BindingSource mLocalMP;
        List<string> listComboSchedue;
        public mForm()
        {
            InitializeComponent();

            CreateScheduleCollumn(new DateTime(2014, 8, 25), new DateTime(2014, 11, 25));
            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
            {
                if (col.Tag == "Value")
                {
                    col.Visible = !TeamAppear;
                }
                if (col.Tag == "Team" || col.Tag == "TeamSchedule")
                {
                    col.Visible = TeamAppear;
                }
            }
            listComboSchedue = new List<string>();
            listComboSchedue = CodeDetail.GetStringForComboByName("Schedule");
            rI_ccbForSchedule.Items.AddRange(listComboSchedue);
            rI_ccbForSchedule.AllowNullInput = DevExpress.Utils.DefaultBoolean.True;
            rI_ccbForSchedule.AutoComplete = true;
            Global.mProject = new Business.Project();
            Global.mProject.ID = 66;
            Global._UserInfo = new Common.UserInfo();
            Global._UserInfo.UserID = 1;

            Business.Team.GetTeamList(ref Global.listTeam);
            Business.CodeDetail.GetPOSMForCombo(ref Global.listPOSM);

            Global.myMP = myMasterPlan.getByProjectID(Global.mProject.ID);
            mLocalMP = new BindingSource();
            mLocalMP.DataSource = Global.myMP;
            gridControl.DataSource = mLocalMP;
        }

        private void mForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                CreateMasterPlanSimple frm = new CreateMasterPlanSimple();
                frm.ShowDialog();
            }
            else if (e.KeyCode == Keys.F2)
            {
                CreateRegion frm = new CreateRegion(this);
                frm.ShowDialog();
            }
        }

        private void mForm_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void gridControl_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void btnRegion_Click(object sender, EventArgs e)
        {
            CreateRegion frm = new CreateRegion(this);
            frm.ShowDialog();
        }

        private void btnPJ_Click(object sender, EventArgs e)
        {
            CreateMasterPlanSimple frm = new CreateMasterPlanSimple();
            frm.ShowDialog();
        }

        private void mForm_Load(object sender, EventArgs e)
        {

        }

        internal void addCheckedRegions(List<Business.Region> data, string RegionFatherName)
        {
            string messageError = "";
            
            if (RegionFatherName != "")
            {
                if (!Global.myMP.Exists(a => a.ParentName.Trim() == RegionFatherName))
                {
                    string newCode = Business.ProjectRegion.CreateCode(Global.mProject.ID);

                    List<ProjectRegion> newPR = new List<ProjectRegion>();

                    ProjectRegion dPR = new ProjectRegion();
                    dPR.ProjectID = Global.mProject.ID;
                    dPR.RegionCode = newCode;
                    dPR.RegionLevel = 3;
                    dPR.RegionName = RegionFatherName;
                    dPR.Status = (int)Common.STATUS_CODE.ROW_STATUS.ACTIVE;
                    dPR.CreatedBy = Global._UserInfo.UserID;
                    dPR.CreatedDateTime = DateTime.Now;
                    dPR.RowVersion = 1;
                    newPR.Add(dPR);

                    foreach (Business.Region item in data)
                    {
                        ProjectRegion pr = new ProjectRegion();
                        pr.ProjectID = Global.mProject.ID;
                        pr.ParentCode = newCode;
                        pr.RegionCode = item.RegionCode;
                        pr.RegionLevel = item.RegionLevel;
                        pr.RegionName = item.RegionName;

                        newPR.Add(pr);
                    }

                    Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW errCode =
                        Business.ProjectRegion.AddNew(ref messageError, ref newPR, ref Global._UserInfo);
                    if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SUCCESS)
                    {
                        newPR.RemoveAll(p => p.RegionLevel == 3);
                        foreach (var item in newPR)
                        {
                            mLocalMP.Add(new myMasterPlan
                            {
                                ID = Global.mProject.ID,
                                ParentCode = newCode,
                                ParentName = RegionFatherName,
                                RegionCode = item.RegionCode,
                                RegionName = item.RegionName,
                                ProjectRegionID = item.ID
                            });
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Tên miền đã bị trùng!");
                }
            }
            else
            {
                MessageBox.Show("Tên miền trống!");
            }
        }

        #region ProjectMechanicism
        internal void addCheckedMechanicism(List<CodeDetail> listChecked)
        {
            string messageError = "";

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            List<ProjectMechanicism> newPM = new List<ProjectMechanicism>();
            foreach (CodeDetail item in listChecked)
            {
                ProjectMechanicism pm = new ProjectMechanicism();
                pm.ProjectID = Global.mProject.ID;
                pm.ProjectRegion = (long)m.ProjectRegionID;
                pm.Mechanicism = (int)item.NumberValue;

                newPM.Add(pm);
            }

            Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCodeU = Business.ProjectMechanicism.Update(ref messageError, ref newPM, ref Global._UserInfo);
            if (errCodeU == Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS)
            {
                updateData(newPM);
            }
        }

        private void updateData(List<ProjectMechanicism> newPM)
        {
            string parentCode;
            string parentName;
            long projectRegionID;
            string regionCode;
            string regionName;

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            parentCode = m.ParentCode;
            parentName = m.ParentName;
            projectRegionID = (long)m.ProjectRegionID;
            regionCode = m.RegionCode;
            regionName = m.RegionName;

            Global.myMP.RemoveAll(a => a.ProjectRegionID == projectRegionID);

            foreach (ProjectMechanicism pm in newPM)
            {
                mLocalMP.Add(new myMasterPlan
                {
                    ID = Global.mProject.ID,
                    ParentCode = parentCode,
                    ParentName = parentName,
                    RegionCode = regionCode,
                    RegionName = regionName,
                    ProjectRegionID = pm.ProjectRegion,
                    ProjectMechanismID = pm.ID,
                    MechaValue = pm.Mechanicism,
                    MechaName = Global.listMech.Single(a => a.NumberValue == pm.Mechanicism).CDName
                });
            }

            gridControl.RefreshDataSource();
        }

        private void btnMechanicism_Click(object sender, EventArgs e)
        {
            if (Global.listMech == null)
            {
                Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT errCode = Business.CodeDetail.GetMechanicismForCombo(ref Global.listMech);
                if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT.SYSTEM_ERROR)
                    MessageBox.Show(Common.myString.NETWORK_ERROR);
            }

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            if (m.ProjectRegionID > 0)
            {
                //show region form
                MechanicismFrm frm = new MechanicismFrm(Global.listMech, this);
                frm.StartPosition = FormStartPosition.CenterScreen;
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Vui lòng chọn một vùng miền!");
            }
        }
        #endregion

        bool TeamAppear = false;
        private void ânHiênTeamToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TeamAppear = !TeamAppear;

            foreach (DevExpress.XtraGrid.Columns.GridColumn col in gridView.Columns)
            {
                if (col.Tag == "Value")
                {
                    col.Visible = !TeamAppear;
                }
                if (col.Tag == "Team" || col.Tag == "TeamSchedule")
                {
                    int visibleIndex = 0;
                    if (col.Name.Split('_').Count() > 1)
                        int.TryParse(col.Name.Split('_')[1], out visibleIndex);
                    col.VisibleIndex = visibleIndex + 10;
                    col.Visible = TeamAppear;
                }
            }
        }

        private void CreateScheduleCollumn(DateTime startDate, DateTime endDate)
        {
            int index = 1;
            while (startDate <= endDate)
            {
                DevExpress.XtraGrid.Columns.GridColumn col = new DevExpress.XtraGrid.Columns.GridColumn();
                col.Caption = String.Format("Tháng {0}\n-------------\nNgày {1}\n-------------\nThứ {2}", startDate.Month, startDate.Day, index.ToString("00"));
                col.Tag = "TeamSchedule";
                col.Name = "col_" + index.ToString("00");
                col.FieldName = "col_" + index.ToString("00");
                col.Visible = true;
                col.VisibleIndex = index;
                col.AppearanceHeader.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap;
                col.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                col.AppearanceHeader.Options.UseTextOptions = true;
                col.UnboundType = DevExpress.Data.UnboundColumnType.Object;
                col.ColumnEdit = rI_ccbForSchedule;
                col.MinWidth = 60;
                gridView.ColumnPanelRowHeight = 90;
                startDate = startDate.AddDays(1);
                index++;
                gridView.Columns.Add(col);
            }
        }

        private void gridView_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            myMasterPlan currentRow = mLocalMP[e.ListSourceRowIndex] as myMasterPlan;

            if (e.Column.Tag == "TeamSchedule")
            {
                if (currentRow.ProjectTeamID == null) return;

                if (e.IsGetData)
                {
                    var value = currentRow.schedule_list.Where(p => p.No == int.Parse(e.Column.Name.Split('_')[1])).FirstOrDefault();
                    if (value != null)
                        e.Value = value.WorkTypeName;
                }
                else if (e.IsSetData)
                {
                    int index = listComboSchedue.IndexOf(listComboSchedue.Where(p => p == e.Value.ToString()).FirstOrDefault());
                    if (index >= 0)
                    {
                        var currentSchedue = currentRow.schedule_list.Where(p => p.No == int.Parse(e.Column.Name.Split('_')[1])).FirstOrDefault();
                        if (currentSchedue != null)
                        {
                            currentRow.schedule_list.Where(p => p.No == int.Parse(e.Column.Name.Split('_')[1])).FirstOrDefault().WorkType = index;
                            currentRow.schedule_list.Where(p => p.No == int.Parse(e.Column.Name.Split('_')[1])).FirstOrDefault().WorkTypeName = e.Value.ToString();
                        }
                        else
                        {
                            currentSchedue = new TeamSchedule();
                            currentSchedue.ProjectTeam = currentRow.ProjectTeamID.Value;
                            currentSchedue.No = int.Parse(e.Column.Name.Split('_')[1]);
                            currentSchedue.Date = Common.ConvertUtils.ReturnDateTimeFromNo(currentSchedue.No, new DateTime(2014, 8, 25), new DateTime(2014, 11, 25));
                            currentSchedue.WorkType = index;
                            currentSchedue.WorkTypeName = e.Value.ToString();
                        }
                    }
                }
            }
        }

        #region ProjectChannel
        private void btnChannel_Click(object sender, EventArgs e)
        {
            if (Global.listChannel == null)
            {
                Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT errCode = Business.CodeDetail.GetChannelForCombo(ref Global.listChannel);
                if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_SELECT.SYSTEM_ERROR)
                    MessageBox.Show(Common.myString.NETWORK_ERROR);
            }

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            if (m.ProjectMechanismID > 0)
            {
                //show region form
                ChannelFrm frm = new ChannelFrm(Global.listChannel, this);
                frm.StartPosition = FormStartPosition.CenterScreen;
                frm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Chưa có Mechanicism!");
            }
        }

        internal void addCheckedChannels(List<CodeDetail> listChecked)
        {
            string messageError = "";

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            List<ProjectChannel> newPC = new List<ProjectChannel>();
            foreach (CodeDetail item in listChecked)
            {
                ProjectChannel pc = new ProjectChannel();
                pc.ProjectID = Global.mProject.ID;
                pc.ProjectMechanicism = (long)m.ProjectMechanismID;
                pc.Channel = (int)item.NumberValue;

                pc.NoLocation = 0;
                pc.NoWorkingDayPerLocation = 0;
                pc.NoSessionPerDay = 0;
                pc.AveTrafficPerDay = 0;
                pc.Timing = 1;

                newPC.Add(pc);
            }

            Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCodeU = Business.ProjectChannel.Update(ref messageError, ref newPC, ref Global._UserInfo);
            if (errCodeU == Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS)
            {
                updateData(newPC);
            }
        }

        private void updateData(List<ProjectChannel> newPC)
        {
            string parentCode;
            string parentName;
            long projectRegionID;
            string regionCode;
            string regionName;
            int mechaValue;
            string mechaName;
            long projectMechanismID;

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            parentCode = m.ParentCode;
            parentName = m.ParentName;
            projectRegionID = (long)m.ProjectRegionID;
            regionCode = m.RegionCode;
            regionName = m.RegionName;
            mechaValue = (int)m.MechaValue;
            mechaName = m.MechaName;
            projectMechanismID = (long)m.ProjectMechanismID;

            Global.myMP.RemoveAll(a => a.ProjectMechanismID == projectMechanismID);

            foreach (ProjectChannel pm in newPC)
            {
                mLocalMP.Add(new myMasterPlan
                {
                    ID = Global.mProject.ID,
                    ParentCode = parentCode,
                    ParentName = parentName,
                    RegionCode = regionCode,
                    RegionName = regionName,
                    ProjectRegionID = projectRegionID,
                    ProjectMechanismID = pm.ID,
                    MechaValue = mechaValue,
                    MechaName = mechaName,
                    ProjectChannelID = pm.ID,
                    ChannelValue = pm.Channel,
                    ChannelName = Global.listChannel.Single(a => a.NumberValue == pm.Channel).CDName,
                    NoLocation = pm.NoLocation,
                    NoWorkingDayPerLocation = pm.NoWorkingDayPerLocation,
                    NoSessionPerDay = pm.NoSessionPerDay,
                    AveTrafficPerDay = pm.AveTrafficPerDay
                });
            }

            gridControl.RefreshDataSource();
        }
        #endregion

        #region ProjectTeam
        internal void addTeam(List<Business.CodeDetail> list, string TeamName)
        {
            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            long projectChannelID = (long)m.ProjectChannelID;
            long projectMechanicismID = (long)m.ProjectMechanismID;

            Team t = new Team();
            t.Name = TeamName;
            t.CreatedBy = Global._UserInfo.UserID;

            Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW errCode = Business.Team.AddNew(ref t);
            switch (errCode)
            {
                case Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SUCCESS:
                    MessageBox.Show("Tạo Team thành công!");
                    break;
                case Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SYSTEM_ERROR:
                    MessageBox.Show("Lỗi hệ thống khi tạo Team!");
                    break;
                case Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.DUPPLICATE:
                    MessageBox.Show("Tên Team đã bị trùng!");
                    break;
            }

            if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_ADDNEW.SUCCESS)
            {
                if (Global.listTeam != null) Global.listTeam.Add(t);

                List<ProjectTeam> newPT = new List<ProjectTeam>();

                foreach (Business.CodeDetail item in list)
                {
                    ProjectTeam pt = new ProjectTeam();
                    pt.TeamID = t.ID;
                    pt.ProjectID = Global.mProject.ID;
                    pt.ProjectChannel = projectChannelID;
                    pt.ProjectMechanicism = projectMechanicismID;
                    pt.POSM = (int)item.NumberValue;

                    newPT.Add(pt);
                }

                if (addProjectTeam(newPT))
                {
                    updateData(newPT);
                }
                else
                {
                    MessageBox.Show("Lỗi!");
                }
            }
        }

        private bool addProjectTeam(List<ProjectTeam> listPT)
        {
            string messageError = "";

            Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE errCode = Business.ProjectTeam.Update(ref messageError, ref listPT, ref Global._UserInfo);
            if (errCode == Common.ERROR_CODE.ERROR_CODE_ITEMS_UPDATE.SUCCESS)
            {
                return true;   
            }
            return false;
        }

        private void btnPT_Click(object sender, EventArgs e)
        {
            POSMFrm frm = new POSMFrm(Global.listPOSM, this);
            frm.StartPosition = FormStartPosition.CenterScreen;
            frm.ShowDialog();
        }

        internal void addCheckedPOSM(List<CodeDetail> list, string teamName)
        {
            
        }

        private void updateData(List<ProjectTeam> newPT)
        {
            string parentCode, parentName;
            long projectRegionID;
            string regionCode, regionName;
            int mechaValue; string mechaName;
            long projectMechanismID;
            int channelValue; string channelName;
            long projectChannelID;
            int noLocation, noWorkingDayPerLocation, noSessionPerDay, aveTrafficPerDay;

            myMasterPlan m = (myMasterPlan)gridView.GetFocusedRow();
            parentCode = m.ParentCode;
            parentName = m.ParentName;
            projectRegionID = (long)m.ProjectRegionID;
            regionCode = m.RegionCode;
            regionName = m.RegionName;
            mechaValue = (int)m.MechaValue;
            mechaName = m.MechaName;
            projectMechanismID = (long)m.ProjectMechanismID;
            channelValue = (int)m.ChannelValue;
            channelName = m.ChannelName;
            projectChannelID = (long)m.ProjectChannelID;
            noLocation = (int)m.NoLocation;
            noWorkingDayPerLocation = (int)m.NoWorkingDayPerLocation;
            noSessionPerDay = (int)m.NoSessionPerDay;
            aveTrafficPerDay = (int)m.AveTrafficPerDay;

            Global.myMP.RemoveAll(a => a.ProjectMechanismID == projectMechanismID && a.ProjectChannelID == projectChannelID);

            foreach (ProjectTeam pt in newPT)
            {
                mLocalMP.Add(new myMasterPlan
                {
                    ID = Global.mProject.ID,
                    ParentCode = parentCode,
                    ParentName = parentName,
                    RegionCode = regionCode,
                    RegionName = regionName,
                    ProjectRegionID = projectRegionID,
                    ProjectMechanismID = projectMechanismID,
                    MechaValue = mechaValue,
                    MechaName = mechaName,
                    ProjectChannelID = projectChannelID,
                    ChannelValue = channelValue,
                    ChannelName = channelName,
                    NoLocation = noLocation,
                    NoWorkingDayPerLocation = noWorkingDayPerLocation,
                    NoSessionPerDay = noSessionPerDay,
                    AveTrafficPerDay = aveTrafficPerDay,
                    ProjectTeamID = pt.ID,
                    TeamID = pt.TeamID,
                    TeamName = Global.listTeam.Single(a=>a.ID == pt.TeamID).Name
                });
            }

            gridControl.RefreshDataSource();
        }
        #endregion
    }
}
